package com.hrhr74.penguinstream.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.hrhr74.penguinstream.constant.UserConstant;
import com.hrhr74.penguinstream.domain.dto.UserEditDTO;
import com.hrhr74.penguinstream.domain.po.User;
import com.hrhr74.penguinstream.service.UserEdit;
import com.hrhr74.penguinstream.utils.CodeUtil;
import com.hrhr74.penguinstream.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service(UserConstant.PHONE_EDIT)
public class UserEditPhone extends UserEdit {
    @Autowired
    private CodeUtil  codeUtil;
    /**
     * 修改手机号
     * @param userEditDTO
     * @return
     */
    @Override
    public Result editUser(UserEditDTO userEditDTO) {
        Long id = 1L;//TODO UserContext.getUser();

        if(userEditDTO == null || userEditDTO.getPhone() == null ||
                Objects.equals(userEditDTO.getPhone(), "")
                || userEditDTO.getCode() == null || userEditDTO.getNewPhone()==null){
            return Result.error("不符合当前修改方式！");
        }

        if(userEditDTO.getNewPhone().equals(userEditDTO.getPhone())){
            return Result.error("新旧手机不能相同！");
        }

        User user = Db.lambdaQuery(User.class).eq(User::getId, id).eq(User::getPhone, userEditDTO.getPhone()).one();

        if(user == null){
            return Result.error("旧手机号与当前用户不匹配！");
        }

        String newPhone = userEditDTO.getNewPhone();

        //验证新手机验证码
        boolean checkCode = codeUtil.checkCode(newPhone, userEditDTO.getCode());

        if(!checkCode){
            return Result.error("验证码错误，请重试！");
        }

        //验证新手机号是否已经被使用
        boolean exists = Db.lambdaQuery(User.class).eq(User::getPhone, newPhone).exists();
        if(exists){
            return Result.error("当前手机号已被使用，请使用未被注册过的手机号！");
        }

        boolean update = Db.lambdaUpdate(User.class).set(User::getPhone, newPhone).update();
        return update ? Result.ok("修改成功！") : Result.error("修改失败！");
    }
}
